package com.example.sofa_module.detail.behavior;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.customview.widget.ViewDragHelper;

import com.blankj.utilcode.util.ConvertUtils;

public class VideoScrollBehavior extends CoordinatorLayout.Behavior<View> {

    private ViewDragHelper helper;
    private int height = 0;//滑动缩放的子View高度
    private View refView;//滑动缩放的子view

    public VideoScrollBehavior(Context context, AttributeSet attrs){
        super(context,attrs);
    }

    @Override
    public boolean onLayoutChild(@NonNull CoordinatorLayout parent, @NonNull View child, int layoutDirection) {
        if (helper == null){
            //sensitivity->2次touch采集的密度->值越大move状态时间距越短
            helper = ViewDragHelper.create(parent,1f,callback);
            refView = child;
            height = refView.getMeasuredHeight();
        }
        return super.onLayoutChild(parent, child, layoutDirection);
    }

    @Override
    public boolean onTouchEvent(@NonNull CoordinatorLayout parent, @NonNull View child, @NonNull MotionEvent ev) {
        if (helper == null)
            return false;
        helper.processTouchEvent(ev);
        return true;
    }

    @Override
    public boolean onInterceptTouchEvent(@NonNull CoordinatorLayout parent,
                                         @NonNull View child, @NonNull MotionEvent ev) {
        //区分滑动方向->手指在屏幕中2次滑动点的距离-disx(X轴移动距离);disy(y轴移动距离)
        //disx取绝对值;disy取绝对值->根据滑动角度->区分水平滑动或者垂直滑动
        //ViewDragHelper.Callback->区分垂直水平滑动
        if (helper == null)
            return super.onInterceptTouchEvent(parent, child, ev);
        return helper.shouldInterceptTouchEvent(ev);
    }

    private ViewDragHelper.Callback callback = new ViewDragHelper.Callback() {
        @Override
        public boolean tryCaptureView(@NonNull View child, int pointerId) {
            //当前设置viewdraghelper的view是否可以滑动->true可滑动,false不可以滑动
            return true;
        }

        //子view垂直滑动
        //child->ImageView
        //dy->2次touch事件的间距->dy正:从上向下;dy负:从下向上滑动
        @Override
        public int clampViewPositionVertical(@NonNull View child, int top, int dy) {
            ViewGroup.LayoutParams layoutParams = child.getLayoutParams();
            //
            if (layoutParams.height < 0){
                layoutParams.height = height;
            }
            layoutParams.height +=dy;//当前高度+=每次移动的距离->
            //视频播放最小边界->
            if (layoutParams.height< ConvertUtils.dp2px(200)){
                layoutParams.height = ConvertUtils.dp2px(200);
            }
            if (layoutParams.height > height)
                layoutParams.height = height;
            refView.setLayoutParams(layoutParams);
            return top;
        }
    };

}
